//
//  SXHMapViewController.m
//  ZLZKBaseUtils
//
//  Created by sxh on 2021/4/20.
//

#import "SXHMapViewController.h"
#import <MapKit/MapKit.h>
#import <MapKit/MKAnnotation.h>
#import "SXHLocationHandler.h"

#define IPHONE_HEIGHT    [UIScreen mainScreen].bounds.size.height
#define IPHONE_WIDTH     [UIScreen mainScreen].bounds.size.width
#define TabBarHeight ([[UIApplication sharedApplication] statusBarFrame].size.height>20?83:49)
#define StatusBarHeight [[UIApplication sharedApplication] statusBarFrame].size.height
#define NavibarH ([[UIApplication sharedApplication] statusBarFrame].size.height>20?88.0:64.0)
#define WK(weakSelf) __weak __typeof(&*self)weakSelf = self;

@interface SXHMapViewController ()
<
    MKMapViewDelegate,
    CLLocationManagerDelegate
>

@property (nonatomic, strong) MKMapView *mapView;

@property (nonatomic, strong) UIView *topView;

@property (nonatomic, strong) BackBlock block;

@property (nonatomic, strong) NSString *centerTitle;

// 反检索地址
@property (nonatomic, strong) NSString *address;
// 定位地址坐标
@property (nonatomic, strong) CLLocation *location;

// 显示地址的父视图
@property (nonatomic, strong) UIView *addressView;
// 显示地址的label
@property (nonatomic, strong) UILabel *addressLabel;
///初始化地理编码器
@property (nonatomic, strong) CLGeocoder *geocoder;
///定位服务管理类
@property (nonatomic, strong) CLLocationManager *locationManager;
///重置地图中心坐标并刷新定位
@property (nonatomic, strong) UIButton *resetBtn;

@end

@implementation SXHMapViewController

- (void)dealloc {
    NSLog(@"地图页面被销毁");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
}

- (instancetype)initWithTitle:(NSString *)title complete:(BackBlock)complete {
    
    if (self = [super init]) {
        
        _block = complete;
        
        _centerTitle = title;
        
        [self initView];
        
        [self startLocation];
    }
    return self;
}

- (void)initView {

    [self mapView];
    
    [self topView];
    
    [self resetBtn];
}

- (void)goback {
    WK(weakSelf)
    NSError *error = [[NSError alloc] initWithDomain:@"localhost" code:500 userInfo:@{NSLocalizedDescriptionKey:@"用户自主退出"}];
    [self dismissViewControllerAnimated:YES completion:^{
        weakSelf.block(nil, nil, error);
    }];
}

- (void)goSure {
    WK(weakSelf)
    [self dismissViewControllerAnimated:YES completion:^{
        weakSelf.block(weakSelf.location, weakSelf.address, nil);
    }];
}

- (void)reset {
    
    [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(self.location.coordinate, 2000, 2000) animated:YES];
}

- (void)startLocation {
//    WK(weakSelf)
    
    // 获取用户权限
    
    // 显示定位按钮
    [self mapView];
    
//    [[SXHLocationHandler shared] startLocation:^(CLLocation * _Nonnull location, NSString * _Nullable address) {
//
//        weakSelf.location = location;
//
//        [weakSelf.mapView setCenterCoordinate:location.coordinate];
//        //设置地图显示范围
//        [weakSelf.mapView setRegion:MKCoordinateRegionMakeWithDistance(location.coordinate, 2000, 2000) animated:YES];
//
//        if (@available(iOS 13.0, *)) {
//            MKPointAnnotation *point = [[MKPointAnnotation alloc] initWithCoordinate:location.coordinate title:[address stringByReplacingOccurrencesOfString:@"," withString:@""] subtitle:@""];
//            [weakSelf.mapView addAnnotation:point];
//        } else {
//            // Fallback on earlier versions
//        }
//
//        weakSelf.address = address;
//    }];
}


- (NSBundle *)getBundle {
    
    NSString *mainStr = [[NSBundle mainBundle] bundlePath];
    
    NSString *moduleStr1 = [mainStr stringByAppendingPathComponent:@"ZLZKBaseUtils.bundle"];
    NSBundle *module1 = [NSBundle bundleWithPath:moduleStr1];
    
    NSString *moduleStr2 = [mainStr stringByAppendingPathComponent:@"Frameworks/ZLZKBaseUtils.framework/ZLZKBaseUtils.bundle"];
    NSBundle *module2 = [NSBundle bundleWithPath:moduleStr2];
    return module1 ?: module2;
}

#pragma mark - MKMapViewDelegate

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    WK(weakSelf)
    _location = userLocation.location;
    //设置地图显示范围
    [mapView setRegion:MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000) animated:YES];
    
    mapView.showsUserLocation = NO;
    [self.locationManager stopUpdatingLocation];
    
    // 反检索
    _geocoder = [[CLGeocoder alloc] init];
    [_geocoder reverseGeocodeLocation:_location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//        mapView.showsUserLocation = NO;
            if (placemarks.count > 0) {
                CLPlacemark *placemark = [placemarks objectAtIndex:0];
                NSLog(@"%@",placemark.name);
                //获取城市
                NSString *city = placemark.locality;
                if (!city) {
                    //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                    city = placemark.administrativeArea;
                }
                // 位置名
                NSLog(@"name,%@",placemark.name);
                // 街道
                NSLog(@"thoroughfare,%@",placemark.thoroughfare);
                // 子街道
                NSLog(@"subThoroughfare,%@",placemark.subThoroughfare);
                // 市
                NSLog(@"locality,%@",placemark.locality);
                // 区
                NSLog(@"subLocality,%@",placemark.subLocality);
                // 国家
                NSLog(@"country,%@",placemark.country);
                NSString *address = [NSString stringWithFormat:@"%@%@%@%@%@%@", placemark.country, placemark.administrativeArea, placemark.locality, placemark.subLocality, placemark.thoroughfare, placemark.name];
//                @try {
//                    address = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] lastObject];
//                } @catch (NSException *exception) {
//                    NSLog(@"错误信息%@",exception.userInfo);
//                } @finally {
//                    
//                }
                weakSelf.address = address;
                MKPointAnnotation *point = [[MKPointAnnotation alloc] init];
                point.coordinate = weakSelf.location.coordinate;
                point.title = [address stringByReplacingOccurrencesOfString:@"," withString:@""];
                [weakSelf.mapView addAnnotation:point];
            }else if (error == nil && [placemarks count] == 0) {
                NSLog(@"No results were returned.");
            } else if (error != nil){
                NSLog(@"An error occurred = %@", error);
            }
    }];
}

- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error {
    NSLog(@"定位失败:%@", error);
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    
    NSLog(@"%@-----%@", annotation.title, annotation.subtitle);
//    if ([annotation isKindOfClass:[MKUserLocation class]]) {
    if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
        
//        MKAnnotationView *location = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"point"];
//        location.canShowCallout = YES;
//
//        location.image = [UIImage imageNamed:@"point" inBundle:[self getBundle] compatibleWithTraitCollection:nil];
//        return location;
    
        MKPinAnnotationView *location = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"point"];
        
        location.canShowCallout = YES;
        
        location.calloutOffset = CGPointMake(0, 0);
        
        location.image = [UIImage imageNamed:@"point" inBundle:[self getBundle] compatibleWithTraitCollection:nil];
//        location.leftCalloutAccessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"point" inBundle:[self getBundle] compatibleWithTraitCollection:nil]];
        return location;
    }
    return nil;
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {

//    if (status == kCLAuthorizationStatusNotDetermined) {
//        //跳转到设置详情页
//        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
//        if ([[UIApplication sharedApplication] canOpenURL:url]) {
//            
//            [[UIApplication sharedApplication] openURL:url];
//        }
//    }
    
    if (status == kCLAuthorizationStatusDenied) { // 拒绝了定位权限
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您已拒绝获取定位权限,无法获取定位" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //跳转到设置详情页
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
            }
        }];
        [alert addAction:ok];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

#pragma mark - setter && getter
- (MKMapView *)mapView {
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, NavibarH, IPHONE_WIDTH, IPHONE_HEIGHT)];
        
        _mapView.delegate = self;
        // 默认地图
        _mapView.mapType = MKMapTypeStandard;
        
        // 显示建筑物
        _mapView.showsBuildings = YES;
        
        // 指南针
        _mapView.showsCompass = NO;
        
        // 兴趣点
        _mapView.showsPointsOfInterest = YES;
        
        // 显示比例尺
        _mapView.showsScale = YES;
        
        // 交通
        _mapView.showsTraffic = YES;
        
        _mapView.showsUserLocation = YES;
        
        // 自动放大地图到合适比例尺
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
//        _mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
        
        // 获取授权
        [self locationManager];
        
        [self.view addSubview:_mapView];
    }
    return _mapView;
}

- (UIView *)topView {
    if (!_topView) {
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, NavibarH)];
        
        // 返回按钮
        UIButton *back = [[UIButton alloc] initWithFrame:CGRectMake(0, NavibarH - 44, 80, 44)];
        
        [back setTitle:@"取消" forState:UIControlStateNormal];
        
        back.titleLabel.font = [UIFont systemFontOfSize:15];
        
        [back setTitleColor:[UIColor grayColor] forState:0];
        
        [back addTarget:self action:@selector(goback) forControlEvents:UIControlEventTouchUpInside];
        
        [_topView addSubview:back];
        
        // 确认按钮
        UIButton *sure = [[UIButton alloc] initWithFrame:CGRectMake(IPHONE_WIDTH - 80, NavibarH - 44, 80, 44)];
        
        [sure setTitle:@"确认" forState:UIControlStateNormal];
        
        sure.titleLabel.font = [UIFont systemFontOfSize:15];
        
        [sure setTitleColor:[UIColor greenColor] forState:0];
        
        [sure addTarget:self action:@selector(goSure) forControlEvents:UIControlEventTouchUpInside];
        
        [_topView addSubview:sure];
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake((IPHONE_WIDTH - 150) / 2, NavibarH - 44, 150, 44)];
        
        title.text = _centerTitle;
        
        title.textAlignment = NSTextAlignmentCenter;
        
        [_topView addSubview:title];
        
        
        [self.view addSubview:_topView];
    }
    return _topView;
}

- (UIView *)addressView {
    if (!_addressView) {
        _addressView = [[UIView alloc] initWithFrame:CGRectMake(16, NavibarH + 8, IPHONE_WIDTH - 32, 60)];
        
        _addressView.backgroundColor = [UIColor whiteColor];
        _addressView.layer.cornerRadius = 5;
        _addressView.layer.masksToBounds = YES;
        
        // 定位图标
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(16, 22, 16, 16)];
        imageView.image = [UIImage imageNamed:@"dingwei" inBundle:[self getBundle] compatibleWithTraitCollection:nil];
        [_addressView addSubview:imageView];
        
        // 地址详情文本
        UILabel *address = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, _addressView.frame.size.width - 40, 60)];
        address.font = [UIFont systemFontOfSize:14];
        address.numberOfLines = 0;
        _addressLabel = address;
        
        [_addressView addSubview:_addressLabel];
        
        [self.view addSubview:_addressView];
    }
    return _addressView;
}

- (void)setAddress:(NSString *)address {
    _address = address;
    [self addressView];
    
    self.addressLabel.text = [address stringByReplacingOccurrencesOfString:@"," withString:@""];
}

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        [_locationManager requestAlwaysAuthorization];
        _locationManager.delegate = self;
        // 定位精度到米
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 过滤器为空
        _locationManager.distanceFilter = kCLDistanceFilterNone;
    }
    return _locationManager;
}

- (UIButton *)resetBtn {
    if (!_resetBtn) {
        _resetBtn = [[UIButton alloc] initWithFrame:CGRectMake(IPHONE_WIDTH - 60, IPHONE_HEIGHT - TabBarHeight + 20, 32, 32)];
        
        [_resetBtn setImage:[UIImage imageNamed:@"reset" inBundle:[self getBundle] compatibleWithTraitCollection:nil] forState:0];
        
        [_resetBtn addTarget:self action:@selector(reset) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:_resetBtn];
    }
    return _resetBtn;
}

@end
